﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EasyTrader.Chart
{
    using PriceWaveList = List<EasyTrader.Wave.PriceWave>;
    using PricePointList = List<EasyTrader.Wave.PricePoint>;
    public partial class CmeMstChartFrm : System.Windows.Forms.Form
    {
        private double curCloseVal = 0.0;
        public CmeMstChartFrm()
        {
            InitializeComponent();
        }

        private void InitControl()
        {
            CmeMstChartCtrl.Series["지수"].ToolTip = "#VALX : #VAL";
            CmeMstChartCtrl.Series["파동"].ToolTip = "#VALX : #VAL";
            cbShowWave.Checked = true;
            cbShowPrice.Checked = false;
        }
        // Wave Manager
        private EasyTrader.Wave.WaveManager m_WaveManager = new EasyTrader.Wave.WaveManager();
        public EasyTrader.Wave.WaveManager WaveManager
        {
            get { return m_WaveManager; }
            set { m_WaveManager = value; }
        }

        int curChartType = 0;
        // Cybos Plus Data Set Member
        private ETDataSet m_CPDataSet = null;
        public EasyTrader.ETDataSet CPDataSet
        {
            get { return m_CPDataSet; }
            set { m_CPDataSet = value; }
        }
        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private void InitTimer()
        {
            timer.Interval = 1000;
            timer.Tick += new EventHandler(OnTimerTick);
            timer.Start();
        }

        // 여기서 차트를 갱신해 준다.
        private void OnTimerTick(object sender, EventArgs e)
        {
            // 차트에 데이터를 대응시켜 준다.
            SetChartData();
            // 파동을 그려준다.
            if (m_WaveManager != null)
            {
                // 파동을 만들어 놓는다.
                m_WaveManager.MakeWaveListFromCmeMst();
                PriceWaveList curWaveList = m_WaveManager.ArragedWaveList;
                //SetWaveOnChart(curWaveList);
            }
            ShowCurValue();
        }

        private void ShowCurValue()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null || GlobalVar.CmeMstDataDownloaded == false)
                return;

            CmeMstTable dataTable = m_CPDataSet.GetCmeMstTable();
            if (dataTable == null)
                return;
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0)
                return;

            DataRow row = dataTable.Rows[rowCount - 1];
            //double closeValue = Convert.ToDouble(row["종가"]);
            string curTime = row["시각"].ToString();
            if (curTime != "0")
            {
                string minText = curTime.Substring(curTime.Length - 2, 2);
                string hourText = curTime.Substring(0, curTime.Length - 2);

                txtCurTime.Text = "현재시간 " + hourText + " : " + minText;
                txtCurPrice.Text = "현재가격 " + curCloseVal.ToString("F2");
            }
        }

        private void SetWaveOnChart(PriceWaveList a_WaveList)
        {
            // 먼저 이전에 모든 점들을 없애 준다.
            CmeMstChartCtrl.Series["파동"].Points.Clear();
            for (int i = 0; i < a_WaveList.Count; i++)
            {
                EasyTrader.Wave.PriceWave wave = a_WaveList[i];
                //if (wave.StartY == 0)
                //    continue;
                CmeMstChartCtrl.Series["파동"].Points.AddXY(wave.StartX, wave.StartY);
                //FutOptChartCtrl.Series["파동"].Points[i].AxisLabel = wave.StartPoint.XValue.ToString();
                // 파동은 마지막 점을 한번 더 넣어 준다.
                if (i == a_WaveList.Count - 1)
                {
                    CmeMstChartCtrl.Series["파동"].Points.AddXY(wave.EndX, wave.EndY);
                    //newSeries.Points[i + 1].AxisLabel = wave.EndPoint.XValue.ToString();
                }
            }
        }



        private void SetChartData()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null || GlobalVar.CmeMstDataDownloaded == false)
                return;

            CmeMstChartCtrl.Series["지수"].Points.Clear();
            CmeMstTable dataTable = m_CPDataSet.GetCmeMstTable();
            double maxValue = -10000.0;
            double minValue = 10000.0;
            int rowCount = dataTable.GetRowCount();
            double highValue = 0;
            double lowValue = 0;
            double openValue = 0;
            double closeValue = 0;
            for (int i = 0; i < rowCount; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["고가"] == DBNull.Value)
                        continue;

                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    closeValue = Convert.ToDouble(row["종가"]);
                    curCloseVal = closeValue;
                    if (i == rowCount - 1 && closeValue == 0)
                        continue;

                    if (curChartType == 0)
                    {
                        CmeMstChartCtrl.Series["지수"].Points.AddXY(i, highValue);
                        CmeMstChartCtrl.Series["지수"].Points[i].XValue = i;
                        //CmeMstChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        CmeMstChartCtrl.Series["지수"].Points[i].YValues[1] = lowValue;
                        CmeMstChartCtrl.Series["지수"].Points[i].YValues[2] = openValue;
                        CmeMstChartCtrl.Series["지수"].Points[i].YValues[3] = closeValue;
                        int hour = Convert.ToInt32(row["시각"]);
                        if (hour != 0)
                            CmeMstChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        else
                            CmeMstChartCtrl.Series["지수"].Points[i].AxisLabel = GlobalVar.NightIndexToTime(i).ToString();
                    }
                    else
                    {
                        CmeMstChartCtrl.Series["지수"].Points.AddXY(i, closeValue);
                        CmeMstChartCtrl.Series["지수"].Points[i].XValue = i;
                        //CmeMstChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        //Console.WriteLine(CmeMstChartCtrl.Series["지수"].Points.Count.ToString());

                        int hour = Convert.ToInt32(row["시각"]);
                        if (hour != 0)
                            CmeMstChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        else
                            CmeMstChartCtrl.Series["지수"].Points[i].AxisLabel = GlobalVar.NightIndexToTime(i).ToString();
                    

                    }

                    if (highValue != 0 && highValue > maxValue)
                    {
                        maxValue = highValue;
                    }

                    if (lowValue != 0 && lowValue > maxValue)
                    {
                        maxValue = lowValue;
                    }

                    if (openValue != 0 && openValue > maxValue)
                    {
                        maxValue = openValue;
                    }

                    if (closeValue != 0 && closeValue > maxValue)
                    {
                        maxValue = closeValue;
                    }

                    if (highValue != 0 && highValue < minValue)
                    {
                        minValue = highValue;
                    }

                    if (lowValue != 0 && lowValue < minValue)
                    {
                        minValue = lowValue;
                    }

                    if (openValue != 0 && openValue < minValue)
                    {
                        minValue = openValue;
                    }

                    if (closeValue != 0 && closeValue < minValue)
                    {
                        minValue = closeValue;
                    }
                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            double valueHeight = maxValue - minValue;
            double ceilVal = Math.Ceiling(valueHeight);
            maxValue = minValue + ceilVal;

            if (maxValue >= minValue)
            {
                CmeMstChartCtrl.ChartAreas["Price"].AxisY.Minimum = minValue;
                CmeMstChartCtrl.ChartAreas["Price"].AxisY.Maximum = maxValue;
            }
        }

        public CmeMstChartFrm(ETDataSet a_DataSet)
        {
            InitializeComponent();
            m_CPDataSet = a_DataSet;
            InitControl();
        }

        private void InitChart()
        {
            CmeMstChartCtrl.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(211)), ((System.Byte)(223)), ((System.Byte)(240)));
            CmeMstChartCtrl.BackSecondaryColor = System.Drawing.Color.White;
            CmeMstChartCtrl.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            CmeMstChartCtrl.BorderlineColor = System.Drawing.Color.FromArgb(((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            CmeMstChartCtrl.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            CmeMstChartCtrl.BorderlineWidth = 2;
            CmeMstChartCtrl.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;

            CmeMstChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.Interval = 30;
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.Interval = 30;
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.Interval = 1;
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.Interval = 1;

            CmeMstChartCtrl.ChartAreas["Price"].Area3DStyle.IsClustered = true;
            CmeMstChartCtrl.ChartAreas["Price"].Area3DStyle.Perspective = 10;
            CmeMstChartCtrl.ChartAreas["Price"].Area3DStyle.IsRightAngleAxes = false;
            CmeMstChartCtrl.ChartAreas["Price"].Area3DStyle.WallWidth = 0;
            CmeMstChartCtrl.ChartAreas["Price"].Area3DStyle.Inclination = 15;
            CmeMstChartCtrl.ChartAreas["Price"].Area3DStyle.Rotation = 10;
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.IsLabelAutoFit = true;
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = false;
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.IsLabelAutoFit = true;
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.IsStartedFromZero = false;
            //CmeMstChartCtrl.ChartAreas["Price"].AxisY.LabelAutoFitMaxFontSize;
            CmeMstChartCtrl.ChartAreas["Price"].BackColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(165)), ((System.Byte)(191)), ((System.Byte)(228)));
            CmeMstChartCtrl.ChartAreas["Price"].BackSecondaryColor = System.Drawing.Color.White;
            CmeMstChartCtrl.ChartAreas["Price"].BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            CmeMstChartCtrl.ChartAreas["Price"].BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            CmeMstChartCtrl.ChartAreas["Price"].BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            CmeMstChartCtrl.ChartAreas["Price"].Position.Auto = true;
            //CmeMstChartCtrl.ChartAreas["Price"].Position.Height = 80F;
            //CmeMstChartCtrl.ChartAreas["Price"].Position.Width = 80F;
            //CmeMstChartCtrl.ChartAreas["Price"].Position.X = 5F;
            //CmeMstChartCtrl.ChartAreas["Price"].Position.Y = 10F;
            CmeMstChartCtrl.ChartAreas["Price"].ShadowColor = System.Drawing.Color.Transparent;
            if (GlobalVar.FutOptChartType == 0)
            {
                CmeMstChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                comboCmeMstChartType.SelectedIndex = 0;
            }
            else
            {
                CmeMstChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                comboCmeMstChartType.SelectedIndex = 1;
            }

            CmeMstChartCtrl.Series[0]["PriceUpColor"] = "Red";
            CmeMstChartCtrl.Series[0]["PriceDownColor"] = "Blue";
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = true;
            CmeMstChartCtrl.ChartAreas["Price"].AxisX.IsMarginVisible = true;
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.IsEndLabelVisible = true;
            CmeMstChartCtrl.ChartAreas["Price"].AxisY.IsMarginVisible = true;
            //CmeMstChartCtrl.Series[0].Color = Color.Red;
            //DataPointCustomProperties aa = CmeMstChartCtrl.Series[0]["PriceUpColor"];
        }

        private void CmeMstChartFrm_Load(object sender, EventArgs e)
        {
            InitChart();
            InitTimer();
            curChartType = GlobalVar.CmeMstChartType;
            m_WaveManager.EasyTraderDataSet = m_CPDataSet;
            GlobalVar.CmeMstRefCount++;
        }

        private void CmeMstChartFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer.Stop();
            GlobalVar.CmeMstRefCount--;
        }

        private void comboCmeCurrChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            curChartType = comboCmeMstChartType.SelectedIndex;
            if (curChartType != -1)
            {
                if (curChartType == 0)
                {
                    CmeMstChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                }
                else
                {
                    CmeMstChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                }
                SetChartData();
                CmeMstChartCtrl.Invalidate();
            }
        }
    }
}
